from PIL import Image
import os
from shuogg import file_util


def resize_by_x(x, path, new_path):
    im = Image.open(path)
    x_old, y_old = im.size
    x_new = x
    y_new = y_old * x_new // x_old
    out = im.resize((x_new, y_new), Image.ANTIALIAS)
    out.save(new_path)


def resize_by_y(y, path, new_path):
    im = Image.open(path)
    x_old, y_old = im.size
    y_new = y
    x_new = x_old * y_new // y_old
    out = im.resize((x_new, y_new), Image.ANTIALIAS)
    out.save(new_path)


def resize(x, y, path, new_path):
    im = Image.open(path)
    out = im.resize((x, y), Image.ANTIALIAS)
    out.save(new_path)


def resize_quick(x, y, path):
    p, n = os.path.split(path)
    index = n.rfind('.')
    new_name = n[:index] + '_1' + n[index:]
    new_path = p + new_name
    im = Image.open(path)
    out = im.resize((x, y), Image.ANTIALIAS)
    out.save(new_path)


def resize_x_batch(x, path, cover=False):
    files = file_util.get_files_fullpath(path)
    for f in files:
        if f.endswith('.jpg') or f.endswith('.png'):
            p, n = os.path.split(f)
            index = n.rfind('.')
            if not cover:
                new_name = n[:index] + '_1' + n[index:]
            else:
                new_name = n[:index] + n[index:]
            new_path = p + os.sep + new_name
            resize_by_x(x, f, new_path)
            print(f)


def resize_batch(x, y, path, cover=False):
    files = file_util.get_files_fullpath(path)
    for f in files:
        if f.endswith('.jpg') or f.endswith('.png'):
            p, n = os.path.split(f)
            index = n.rfind('.')
            if not cover:
                new_name = n[:index] + '_1' + n[index:]
            else:
                new_name = n[:index] + n[index:]
            new_path = p + os.sep + new_name
            resize(x, y, f, new_path)
            print(f)

def re_scale(scale, path):
    im = Image.open(path)
    new_x, new_y = int(scale * im.size[0]), int(scale * im.size[1])
    out = im.resize((new_x, new_y), Image.ANTIALIAS)
    out.save(path)


# resize_batch(25,25, '.', True)
